package cz.tomasdvorak.cars.resources;

import cz.tomasdvorak.cars.CarExpensesApp;
import cz.tomasdvorak.cars.dto.ImageItem;
import cz.tomasdvorak.cars.utils.ImagesUtils;
import cz.tomasdvorak.cars.wicket.resources.ImageResourceState;
import org.apache.log4j.Logger;
import org.apache.wicket.markup.html.DynamicWebResource;
import org.apache.wicket.util.time.Time;
import org.apache.wicket.util.value.ValueMap;

import java.io.IOException;

public class ImageResource extends DynamicWebResource {

    private ImageResourceState defaultImage;
    private static final int MAX_THUMB_SIZE = 100;

    public void setDefaultImage(ImageResourceState defaultImage) {
        this.defaultImage = defaultImage;
    }

    private static final Logger log = Logger.getLogger(ImageResource.class);

    @Override
    protected ResourceState getResourceState() {
        ValueMap map = getParameters();
        Integer id = map.getAsInteger("id");
        ImageItem image = null;
        try {
            image = ((CarExpensesApp) CarExpensesApp.get()).getVehiclesDao().getImage(id);
            if (image == null) {
                return defaultImage;
            }

            ImageResourceState state = new ImageResourceState(Time.valueOf(image.getLastModify()));

            state.setContentType(image.getMime());
            state.setData(image.getData());
            if(map.getAsBoolean("thumbnail", false)) {
                return scale(state);
            }
            return state;
        } catch (IOException e) {
            log.error(e);
            return null;
        }
    }

    private ResourceState scale(ImageResourceState state) throws IOException {
        return new ImageResourceState("image/jpg", ImagesUtils.scaleImage(state.getData(),
                MAX_THUMB_SIZE), state.lastModifiedTime());
    }
}
